import { ADType, DataCallback, SDKState } from "../SDKDefine";
import SDKAd from "./SDKAd";
import { SDKAdFactory } from "./SDKAdFactory";
export class SDKAdMgr {

    protected ad: SDKAd[] = []

    protected _cfg: ADType = null;

    static create(cfg: ADType) {
        let ins = new SDKAdMgr();
        ins.init(cfg)
        return ins;
    }

    init(cfg: ADType) {
        this._cfg = cfg;
        let ids = this._cfg.ids;
        for (let index = 0; index < ids.length; index++) {
            let ins = SDKAdFactory.build(cfg.name);
            if (ins) {
                this.ad[index] = ins
            }
            if (!cfg.isMultiple) {
                break;
            }
        }
    }

    has() {
        return this.ad.length > 0
    }

    open(param: { callback?: DataCallback, index?: number }) {
        let index = param.index;
        if (index == undefined) {
            index = 0;
        }
        let idx = 0;
        if (this._cfg.isMultiple) {
            idx = index;
        }
        if (this.ad[idx]) {
            this.ad[idx].setAdUnitId(this._cfg.ids[index])
            this.ad[idx].open(param)
        }
    }

    preload(logicState: SDKState, index: number = 0) {
        let idx = 0;
        if (this._cfg.isMultiple) {
            idx = index;
        }
        if (this.ad[idx]) {
            this.ad[idx].preload(logicState)
        }
    }
    close(index: number = 0) {
        let idx = 0;
        if (this._cfg.isMultiple) {
            idx = index;
        }
        if (this.ad[idx]) {
            this.ad[idx].close()
        }
    }
}